package com.qf.mybatis925.filter;


import com.qf.mybatis925.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * --- 天道酬勤 ---
 *
 * @author QiuShiju
 * @desc
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = jwtUtils.getToken(request);
        // 如果jwt不为空，并且认证信息还未放入上下文，则解析jwt
        if (!ObjectUtils.isEmpty(token) && SecurityContextHolder.getContext().getAuthentication() == null) {
            Claims claims = jwtUtils.parseJWT(token);
            List<?> authorities = claims.get("perms", List.class);

            // 正确处理权限列表，将其转换为逗号分隔的字符串
            StringBuilder authoritiesBuilder = new StringBuilder();
            if (authorities != null && !authorities.isEmpty()) {
                for (int i = 0; i < authorities.size(); i++) {
                    if (i > 0) {
                        authoritiesBuilder.append(",");
                    }
                    // 从Map中提取authority字段
                    Object authorityObj = authorities.get(i);
                    if (authorityObj instanceof Map) {
                        Map<String, Object> authorityMap = (Map<String, Object>) authorityObj;
                        authoritiesBuilder.append(authorityMap.get("authority"));
                    } else {
                        authoritiesBuilder.append(authorityObj.toString());
                    }
                }
            }

            String authoritiesString = authoritiesBuilder.toString();
            UsernamePasswordAuthenticationToken authenticationToken =
                    new UsernamePasswordAuthenticationToken(claims.get("username"),
                            null,
                            AuthorityUtils.commaSeparatedStringToAuthorityList(authoritiesString));
            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            // 放入上下文
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }
        filterChain.doFilter(request, response);
    }
}